package com.ce.util;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.io.CopyStreamException;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import sun.net.ftp.FtpClient;

import com.ce.framework.auth.NetUtil;
import com.ce.framework.context.FrameworkContext;
import com.ce.framework.exception.AppException;
import com.ce.framework.util.GeneratorUUID;
import com.ce.framework.util.LogUtil;
import com.ce.framework.util.StringUtil;
import com.ce.framework.util.SystemContext;
import com.ce.framework.util.Uuid;
import com.ce.framework.util.node.JsonTreeNode;
import com.ce.pub.upload.dao.po.PubFileUploadLog;
import com.ce.sys.ftp.FTPClientSource;
import com.ce.sys.ftp.FtpDownClientSource;
import com.ce.sys.login.model.User;
import com.runqian.base.util.DateTool;


/**
 * 嫦娥软件有限公司 版权所有 2013
 * 创建人： 小觜冰凉
 * 创建时间： 2013-10-8 下午03:19:24
 * 功能描述：文件上传通用类
 * ==================================
 * 修改历史
 * 修改人        修改时间      修改位置（函数名）
 *
 * ==================================
 */
public class NetFileUtil {

	private static FTPClientSource ftpsource;

	private static FtpDownClientSource downFtpSource;

	public final static String TEMP_IMG_PATH = "/portal/tmpImg/";

	public final static String IMG_TYPE = "pic";

	public final static String FILE_TYPE = "file";

	public final static String STATION_MAP_TYPE = "station_map";

	public final static String TECHNIC_DATA_TYPE = "technic_data";

	private static int ftpSuccessedCnt=0;//链接成功的个数

	private static int ftpClosedCnt=0;//成功释放的链接个数

	private static int ftpQZClosedCnt=0;//强制释放的链接个数


	/**
	 * 开发人： 小觜冰凉
	 * 开发时间： 2013-11-8 上午10:31:25
	 * 功能描述：保存图片
	 * 方法的参数和返回值
	 * @param uploadFile
	 * @param userName
	 * @return
	 * @throws AppException
	 * @throws IOException
	 * String
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static String saveImage(File uploadFile,String fileName , String userName) throws AppException,
			IOException {
		String fileType = IMG_TYPE;
		String fileId = GeneratorUUID.generateUUID();
		System.out.println("108-saveImage-fileType="+fileType);
		sendFile(uploadFile, fileName, fileId, fileType, userName);
		return fileId;
	}


	/**
	* 开发人：小觜冰凉
	* 开发日期: 2013-11-10  下午04:20:50
	* 功能描述: 保存文件
	* 方法的参数和返回值:
	* @param uploadFile
	* @param fileName
	* @return
	* @throws AppException
	* @throws IOException
	*/
	public static String saveFile(File uploadFile,String fileName) throws AppException,
			IOException {
		return saveFile(uploadFile,fileName,FILE_TYPE);
	}

	/**
	 * 开发人： 小觜冰凉
	 * 开发时间： 2013-11-8 上午10:31:36
	 * 功能描述：保存文件
	 * 方法的参数和返回值
	 * @param uploadFile
	 * @param fileType
	 * @return
	 * @throws AppException
	 * @throws IOException
	 * String
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static String saveFile(File uploadFile,String fileName ,String fileType) throws AppException,
			IOException {
//		String fileType = FILE_TYPE;
		String fileId = GeneratorUUID.generateUUID();
		System.out.println("152-saveImage-fileType="+fileType);
		sendFile(uploadFile, fileName,fileId , fileType,User.getUserId());
		return fileId;
	}

	/**
	 * 开发人： 小觜冰凉
	 * 开发时间： 2013-11-8 上午10:31:42
	 * 功能描述：保存站场图
	 * 方法的参数和返回值
	 * @param uploadFile
	 * @param userName
	 * @return
	 * @throws AppException
	 * @throws IOException
	 * String
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static String saveStationMap(File uploadFile,String fileName , String userName) throws AppException,
			IOException {
		String fileType = STATION_MAP_TYPE;
		String fileId = GeneratorUUID.generateUUID();
		System.out.println("177-saveImage-fileType="+fileType);
		sendFile(uploadFile, fileName,fileId , fileType,userName);
		return fileId;
	}

	/**
	 * 开发人： 小觜冰凉
	 * 开发时间： 2013-11-8 上午10:31:49
	 * 功能描述：保存技术资料
	 * 方法的参数和返回值
	 * @param uploadFile
	 * @param userName
	 * @return
	 * @throws AppException
	 * @throws IOException
	 * String
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static String saveTechnicData(File uploadFile,String fileName , String userName) throws AppException,
			IOException {
		String fileType = TECHNIC_DATA_TYPE;
		String fileId = GeneratorUUID.generateUUID();
		System.out.println("203s-saveImage-fileType="+fileType);
		sendFile(uploadFile, fileName,fileId , fileType,userName);
		return fileId;
	}

	/**
	 * 开发人： 小觜冰凉
	 * 开发时间： 2013-11-8 上午10:31:58
	 * 功能描述：获取文件下载
	 * 方法的参数和返回值
	 * @param vcId
	 * @return
	 * String
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static String getFileUrl(String vcId) {
		return "/common/loadFile.jsp?vcId=" + vcId;
	}

	/**
	 * 开发人： 小觜冰凉
	 * 开发时间： 2013-11-8 上午10:32:50
	 * 功能描述：获取多个文件下载
	 * 方法的参数和返回值
	 * @param path
	 * @param ids
	 * @param split
	 * @return
	 * String
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static String getFileUrls(String path, String ids, String split) {
		if(StringUtil.isBlank(ids))
			return "";
		if (split == null)
			split = ",";
		StringBuffer url = new StringBuffer();
		String sql = "select vc_id,VC_FILENAME from PUB_T_FILE_UPLOAD_LOG where vc_id in ('"
				+ ids.replaceAll(",", "','") + "')";
		List<?> list = DbUtil.executeSqlQuery(sql, JsonTreeNode.mapper);
		JsonTreeNode node = null;
		for (int i = 0; i < list.size(); i++) {
			node = (JsonTreeNode) list.get(i);
			url.append(split + "<a href='/mis" + getFileUrl(node.getId())
					+ "'>" + node.getText() + "</a>");
		}
		return url.length() > 0 ? url.substring(split.length()) : "";
	}

	public static String getImgsHtml(String ids){
		return getImgsHtml(ids,null);
	}

	public static String getImgsHtml(String ids, String split) {
		if(StringUtil.isBlank(ids))
			return "";
		if (split == null)
			split = "<br>";
		String path = FrameworkContext.getPath();
		//path = "/mis";//此处修改为直接调用框架的路径
		StringBuffer url = new StringBuffer();
		String sql = "select vc_id,VC_FILENAME from PUB_T_FILE_UPLOAD_LOG where vc_id in ('"
				+ ids.replaceAll(",", "','") + "')";
		List<?> list = DbUtil.executeSqlQuery(sql, JsonTreeNode.mapper);
		JsonTreeNode node = null;
		for (int i = 0; i < list.size(); i++) {
			node = (JsonTreeNode) list.get(i);
			url.append(split + node.getText() + split + "<img src='" + path + getFileUrl(node.getId())
					+ "'/>");
		}
		return url.length() > 0 ? url.substring(split.length()) : "";
	}

	public static String getFilesHtml(String ids){
		return getFilesHtml(ids, null);
	}

	public static String getFilesHtml(String ids, String split) {
		if(StringUtil.isBlank(ids))
			return "";
		if (split == null)
			split = "<br>";
		String path = FrameworkContext.getPath();
		//path = "/mis";//此处修改为直接调用框架的路径
		StringBuffer url = new StringBuffer();
		String sql = "select vc_id,VC_FILENAME from PUB_T_FILE_UPLOAD_LOG where vc_id in ('"
				+ ids.replaceAll(",", "','") + "')";
		List<?> list = DbUtil.executeSqlQuery(sql, JsonTreeNode.mapper);
		JsonTreeNode node = null;
		for (int i = 0; i < list.size(); i++) {
			node = (JsonTreeNode) list.get(i);
			url.append(" <a href='"+ path + getFileUrl(node.getId()) +"' target='_blank'>"  + node.getText() + "</a>" +split);
		}
		return url.toString();
	}

	public static String getFileUrls(String ids,String split){
		return getFileUrls(FrameworkContext.getPath(),ids,split);
	}

	public static String getFileUrls(String ids){
		return getFileUrls(ids,",");
	}

	public static String getImageUrl(String vcId) {
		return "/pub/upload/PubUpload_loadFile.action?vcId=" + vcId;
	}


	public static String getImagePath(String fileId){
		String sql = "SELECT VC_CHILD$FOLDER FROM PUB_T_FILE_UPLOAD_LOG WHERE VC_ID ='"
				+ fileId + "'";
		String path = DbUtil.getFirstStringSqlQuery(sql);
		if (path == null)
			path = "oldfile/";
		return path;
	}


	public static String getImageSLPath(String fileId) throws IOException {
		String sql = "SELECT VC_CHILD$FOLDER FROM PUB_T_FILE_UPLOAD_LOG WHERE VC_ID ='"
				+ fileId + "'";
		String path = DbUtil.getFirstStringSqlQuery(sql);
		if (path == null)
			path = "oldfile/";
		return path + fileId + "SL";
	}

	public static InputStream getInputStream(String fileId) throws IOException {
		String sql = "SELECT VC_CHILD$FOLDER FROM PUB_T_FILE_UPLOAD_LOG WHERE VC_ID =?";
		String path = DbUtil.getFirstStringSqlQuery(sql,new Object[]{fileId});
		if (path == null)
			path = "oldfile/";
		return getInputStream(path, fileId);
	}
	public static InputStream getInputStream2(String fileId) throws IOException {

		File f = new File(getFileServerPath(fileId));
		if (f.exists() && f.length() > 0)
			return new FileInputStream(f);


		return null;
	}

	public static InputStream getInputStream(String path, String fileName)
			throws IOException {
		boolean useFtpServer = "true".equals(RegeditUtil
				.getRegeditStringValue("USE_FTP_SERVER"));
		InputStream in = null;

		String base = null;
		if (useFtpServer) {
			String basePath = RegeditUtil.getRegeditStringValue("TEMP_FTP_FILE_PATH");//缓存目录可进行自定义配置
			if(basePath==null){
				basePath = FrameworkContext.getAppPath() + TEMP_IMG_PATH;
			}
			else{
				if(!basePath.endsWith("/")&&!basePath.endsWith("\\"))
					basePath += "/";
			}
			File f = new File(basePath	+ path + fileName);
			if (f.exists() && f.length() > 0)
				return new FileInputStream(f);
			FTPClient ftp_ = getFTPDownClient();
			ftp_.setFileType(FTPClient.BINARY_FILE_TYPE); // 设定以二进制传输
			ftp_.changeWorkingDirectory(path);
			in=ftp_.retrieveFileStream(fileName);

			if(in==null){//文件不存在则从远程同步
				freeFTPClient(ftp_);//释放不成功的ftp链接
				if("true".equals(RegeditUtil.getRegeditStringValue("SYN_FLAG")))
				{
					FTPClient dftp=null;
					FTPClient sftp[]=getFTPClientByRegedit();//源地址
					for(FTPClient client:sftp)
					{
						dftp=getFTPUpClient();//目标地址
						if(StringUtil.isNotBlank(path))
							saveFileOnLocalFileServer(client, dftp, path, fileName);
						if(dftp!=null)
						{
							freeFTPClient(dftp);//释放ftp链接
						}
						if(client!=null)
						{
							freeFTPClient(client);//释放ftp链接
						}
					}
				}
				ftp_ = getFTPDownClient();
				ftp_.setFileType(FTPClient.BINARY_FILE_TYPE); // 设定以二进制传输
				ftp_.changeWorkingDirectory(path);
				in=ftp_.retrieveFileStream(fileName);
			}
			if(in!=null){
				if (!f.getParentFile().exists())
					f.getParentFile().mkdirs();
				FileOutputStream out = new FileOutputStream(f);
				byte[] buff = new byte[8192];
				int len = in.read(buff);
				while (len >= 0) {
					out.write(buff, 0, len);
					len = in.read(buff);
				}
				in.close();
				out.flush();
				out.close();
				freeFTPClient(ftp_);//释放ftp链接
				if(f.length()>1024*1024)//如果大于1M的缓存文件，则在程序退出后删除，以免占用过多的磁盘空间
					f.deleteOnExit();
				in = new FileInputStream(f);
			}
		} else {
			String dir = RegeditUtil.getRegeditStringValue("WEB_SERVER_FILE_DIR");
			//如果没有配置本上目录，则使用默认路径D:/csmisfiles/ftpfile/
			if(dir.length()==0){
				dir = "D:/csmisfiles/ftpfile/";
			}
			String[] dirs = dir.split(";");
			for(int i=dirs.length-1;i>=0;i--){
				dir = dirs[i];
				if (!dir.endsWith("/") && !dir.endsWith("\\"))
					dir = dir + "/";
				base = dir;
				File _tmpFile = new File(base + path + fileName);
				if(_tmpFile.exists()){
					try {
						in = new FileInputStream(_tmpFile);
					} catch (Exception e) {

					}
					break;
				}
			}
			if(in==null){
				Logger.getLogger(NetFileUtil.class).error("文件[" + path + fileName + "]在服务器上找不到！");
			}
		}
		if(in==null){//如果在本服务器未找到文件，则从远程服务器上获取
			String vcDid = DbUtil.getFirstStringSqlQuery("select vc_did from pub_t_file_upload_log where vc_id=?",new Object[]{fileName});
			String url = DbUtil.getFirstStringSqlQuery("select vc_url from sys_t_dblink where vc_id=?", new Object[]{vcDid});
			if(url!=null){
				String ssoid = Uuid.getUuid();
				String dblink = DbUtil.getFirstStringSqlQuery("select vc_dblink from sys_t_dblink where vc_id=?",new Object[]{vcDid});
				DbUtil.executeSqlUpdate("insert into SYS_T_SESSION$INF@"+dblink+"(SESSION_ID,SESSION_VALUE) values(?,?)",new Object[]{ssoid,"super"});
				InputStream netIn = NetUtil.getInputStream(url+fileName+"&SSO_ID="+ssoid);
				String dir = RegeditUtil.getRegeditStringValue("WEB_SERVER_FILE_DIR");
				//如果没有配置本上目录，则使用默认路径D:/csmisfiles/ftpfile/
				if(dir.length()==0){
					dir = "D:/csmisfiles/ftpfile/";
				}
				//如果配置了多个目录，则使用最后一个目录做为存储根路径
				else if(dir.lastIndexOf(";")>=0){
					dir = dir.substring(dir.lastIndexOf(";")+1);
				}
				if (!dir.endsWith("/") && !dir.endsWith("\\"))
					dir = dir + "/";
				dir += path + "/";
				File saveFile = new File(dir);
				if (!saveFile.exists())
					saveFile.mkdirs();
				// 将文件保存到web服务器
				OutputStream streamOut = new FileOutputStream(dir + fileName);
				int bytesRead;
				byte[] buffer = new byte[8129];
				while ((bytesRead = netIn.read(buffer, 0, 8129)) != -1) {
					streamOut.write(buffer, 0, bytesRead);
				}
				streamOut.close();
				netIn.close();
				DbUtil.executeSqlUpdate("delete from SYS_T_SESSION$INF@"+dblink+" where SESSION_ID=?",new Object[]{ssoid});
				in = new FileInputStream(dir + fileName);
			}
		}
		DbUtil.executeSqlUpdate("update pub_t_file_upload_log set n_down=n_down+1,dt_last_down=sysdate() where vc_id=?",new Object[]{fileName});
		return in;
	}



	public static String getFileServerPath(String fileId)
			throws IOException {
		String sql = "SELECT VC_CHILD$FOLDER FROM PUB_T_FILE_UPLOAD_LOG WHERE VC_ID =?";
		String path = DbUtil.getFirstStringSqlQuery(sql,new Object[]{fileId});
		String sql2 = "SELECT VC_FILENAME FROM PUB_T_FILE_UPLOAD_LOG WHERE VC_ID =?";

		String fileName = DbUtil.getFirstStringSqlQuery(sql2,new Object[]{fileId});
		int m=fileName.lastIndexOf(".");
		String fileType=fileName.substring(m, fileName.length());
		if (StringUtil.isBlank(path))
			path = "oldfile/";
		boolean useFtpServer = "true".equals(RegeditUtil
				.getRegeditStringValue("USE_FTP_SERVER"));

		String base = null,realpath="";
		if (useFtpServer) {
			String basePath = RegeditUtil.getRegeditStringValue("TEMP_FTP_FILE_PATH");//缓存目录可进行自定义配置
			if(basePath==null){
				basePath = FrameworkContext.getAppPath() + TEMP_IMG_PATH;
			}
			else{
				if(!basePath.endsWith("/")&&!basePath.endsWith("\\"))
					basePath += "/";
			}
			realpath = basePath	+ path + fileId+fileType;

		} else {
			String dir = RegeditUtil.getRegeditStringValue("WEB_SERVER_FILE_DIR");
			//如果没有配置本上目录，则使用默认路径D:/csmisfiles/ftpfile/
			dir= FrameworkContext.getAppPath();
			if(dir.length()==0){
				dir = "D:/csmisfiles/ftpfile/";
			}
			String[] dirs = dir.split(";");
			for(int i=dirs.length-1;i>=0;i--){
				dir = dirs[i];
				if (!dir.endsWith("/") && !dir.endsWith("\\"))
					dir = dir + "/";
				base = dir;
				realpath = base	+ path + fileId+fileType;
			}

		}
		return realpath;
	}


	public static InputStream getImage(String path, String fileName, int width,
			int height) throws IOException {
		InputStream in = getInputStream(path, fileName);
		if(in==null)
			return new FileInputStream(FrameworkContext.getAppPath()+"/images/no_img.gif");
		//在襄樊程序时发现，如果使用velocity模板引擎时，当调用biContext.drawImage(i, 0, 0, null);该句时，会引起线程停滞，造成首页无法打开
		//if(true)return in;
		try {
			if (width == -1 && height == -1)
				return in;
			BufferedImage bi = ImageIO.read(in);
			if (width == -1)
				width = 2000000000;
			if (height == -1)
				height = 2000000000;
			int w = bi.getWidth();
			int h = bi.getHeight();
			if (w < width && h < height)
				return getInputStream(path, fileName);
			int nw = 0, nh = 0;
			if (w > width) {
				nw = width;
				nh = nw * h / w;
			}
			if (nh > height) {
				nh = height;
				nw = nh * w / h;
			}
			/*
			Image i = bi.getScaledInstance(nw, nh, Image.SCALE_SMOOTH);
			ByteArrayOutputStream bs = new ByteArrayOutputStream();
			bi = new BufferedImage(nw, nh, BufferedImage.TYPE_INT_RGB);
			Graphics2D biContext = bi.createGraphics();
			biContext.drawImage(i, 0, 0, null);
			ImageIO.write(bi, "jpg", bs);
			*/
			AffineTransform transform = new AffineTransform();
			transform.setToScale((double) nw / w, (double) nh / h); // 设置缩放比例

			AffineTransformOp ato = new AffineTransformOp(transform, null);
			BufferedImage bid = new BufferedImage(nw, nh,
					BufferedImage.TYPE_3BYTE_BGR);
			ato.filter(bi, bid);
			ByteArrayOutputStream bs = new ByteArrayOutputStream();
			ImageIO.write(bid, "jpg", bs);
			InputStream is = new ByteArrayInputStream(bs.toByteArray());
			return is;
		} catch (Exception e) {
			//e.printStackTrace();
			Logger.getLogger(NetFileUtil.class).error(e.getMessage());
			return getInputStream(path, fileName);
		}
	}

	/**
	 * 开发人： 小觜冰凉
	 * 开发时间： 2013-11-8 上午10:30:35
	 * 功能描述：生成缩略图，存在imagePathSL路径上
	 * 方法的参数和返回值
	 * @param imagePath
	 * @param imagePathSL
	 * @param width
	 * @param height
	 * void
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static void getImageSL(String imagePath, String imagePathSL,
			int width, int height) {
		try {
			File fi = new File(imagePath); // 大图文件
			File fo = new File(imagePathSL); // 将要转换出的小图文件

			AffineTransform transform = new AffineTransform();
			BufferedImage bis = ImageIO.read(fi);

			int w = bis.getWidth(); // 宽
			int h = bis.getHeight(); // 高
			int nw = 150; // 新宽
			int nh = (nw * h) / w; // 新高
			if (nh > 150) { // 重定义
				nh = 150;
				nw = (nh * w) / h;
			}
			double sx = (double) nw / w; // 宽比例
			double sy = (double) nh / h; // 高比例
			transform.setToScale(sx, sy); // 设置缩放比例

			AffineTransformOp ato = new AffineTransformOp(transform, null);
			BufferedImage bid = new BufferedImage(nw, nh,
					BufferedImage.TYPE_3BYTE_BGR);
			ato.filter(bis, bid);
			ImageIO.write(bid, "jpg", fo);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void loadImageToFile(String url, int width, int height,
			String path) {
		try {
			File tmp_f = new File(FrameworkContext.getAppPath() + TEMP_IMG_PATH
					+ path);
			if (tmp_f.exists())
				return;
			tmp_f.getParentFile().mkdirs();
			String id = url.substring(url.indexOf("vcId=") + 5);
			loadImageToFileById(id, width, height, path);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void loadImageToFileById(String id, int width, int height,
			String path) {
		FileOutputStream bos = null;
		try {
			File tmp_f = new File(FrameworkContext.getAppPath() + TEMP_IMG_PATH
					+ path);
			if (tmp_f.exists() && tmp_f.length() > 0)
				return;
			tmp_f.getParentFile().mkdirs();
			bos = new FileOutputStream(FrameworkContext.getAppPath()
					+ TEMP_IMG_PATH + path);
			String sql = "SELECT VC_CHILD$FOLDER FROM PUB_T_FILE_UPLOAD_LOG WHERE VC_ID ='"
					+ id + "'";
			String cp = DbUtil.getFirstStringSqlQuery(sql);
			if (cp == null)
				cp = "oldfile/";
			InputStream in = getImage(cp, id, width, height);
			BufferedImage bi = ImageIO.read(in);
			int[] a = new int[2];
			a[0] = bi.getWidth(); //获得 宽度
	        a[1] = bi.getHeight(); //获得 高度
			ImageIO.write(bi, "JPEG", bos);
			if (in != null)
				in.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
		}
	}

	public static void loadImageToFileByPath(String path, String fileId,
			String allPath) {
		FileOutputStream bos = null;
		try {

			path = FrameworkContext.getAppPath() + TEMP_IMG_PATH + path;
			if (path.indexOf("/") >= 0)
				path = path.replace("/", "\\");
			File tmp_f = new File(path);
			if (!tmp_f.exists())
				tmp_f.getParentFile().mkdirs();
			bos = new FileOutputStream(path + fileId);
			// bos = new FileOutputStream(path+".jpg");
			// String sql = "SELECT VC_CHILD$FOLDER FROM PUB_T_FILE_UPLOAD_LOG
			// WHERE VC_ID ='" + id + "'";
			// String cp = DbUtil.executeFirstStringSqlQuery(sql);
			InputStream in = new FileInputStream(allPath);
			BufferedImage bi = ImageIO.read(in);
			ImageIO.write(bi, "JPG", bos);
			if (in != null)
				in.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
		}
	}

	/**
	 * 开发人：小觜冰凉 开发日期: 2008-7-25 下午11:00:33 功能描述:
	 * 获取上传用的FTP客户端（APACHE组织提供的FTP上传工具类） 方法的参数和返回值:
	 *
	 * @return
	 */
	public static FTPClient getFTPUpClient() {

		if (ftpsource == null) {
			String ip = RegeditUtil.getRegeditStringValue("FTP_SERVER_IP");
			String username = RegeditUtil
					.getRegeditStringValue("FTP_SERVER_USERNAME");
			String pwd = RegeditUtil.getRegeditStringValue("FTP_SERVER_PWD");
			ftpsource = new FTPClientSource(ip, username, pwd);
		}
		// FTPClient ftp_ = ftpsource.getFtpClient();

		FTPClient ftp_ = new FTPClient();
		try {
			String ip = RegeditUtil.getRegeditStringValue("FTP_SERVER_IP");
			String username = RegeditUtil
					.getRegeditStringValue("FTP_SERVER_USERNAME");
			String pwd = RegeditUtil.getRegeditStringValue("FTP_SERVER_PWD");
			ftp_.connect(ip);
			ftp_.login(username, pwd);
		} catch (Exception e) {
			freeFTPClient(ftp_);
			e.printStackTrace();
		}
		return ftp_;
	}

	/**
	 * 开发人：小觜冰凉 开发日期: 2008-7-25 下午11:01:03 功能描述: 获取下载用的FTP客户端 （SUN公司提供的FTP下载工具类）
	 * 方法的参数和返回值:
	 *
	 * @return
	 */
	static FtpClient getFtpDownClient() {

		if (downFtpSource == null) {
			String ip = RegeditUtil.getRegeditStringValue("FTP_SERVER_IP");
			String username = RegeditUtil
					.getRegeditStringValue("FTP_SERVER_USERNAME");
			String pwd = RegeditUtil.getRegeditStringValue("FTP_SERVER_PWD");
			downFtpSource = new FtpDownClientSource(ip, username, pwd);
		}
		// FtpClient ftp_ = downFtpSource.getFtpClient();

		FtpClient ftp_ = null;
		try {
			String ip = RegeditUtil.getRegeditStringValue("FTP_SERVER_IP");
			String username = RegeditUtil
					.getRegeditStringValue("FTP_SERVER_USERNAME");
			String pwd = RegeditUtil.getRegeditStringValue("FTP_SERVER_PWD");
			ftp_ = new FtpClient(ip);
			ftp_.login(username, pwd);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ftp_;
	}

	public static void sendFile(File uploadFile,String fileName,String fileId,String fileDir, String userId)
			throws AppException, IOException {

		System.out.println("793-sendFile:");
		String saveType = RegeditUtil
				.getRegeditStringValue("USE_FTP_SERVER");
		int i=fileName.lastIndexOf(".");
		String fileType=fileName.substring(i, fileName.length());
		PubFileUploadLog po = new PubFileUploadLog();
		po.setVcId(fileId);
		po.setVcFilename(fileName);
		po.setDtAddTime(new Date());
		po.setVcUserId(userId);
		po.setVcUserName(OrgUtil.getUserName(userId));
		System.out.println("804-sendFile:" + fileDir);
		po.setVcChildFolder(getFilePath("ftpfile/" + fileDir));		System.out.println("805-sendFile:" + po.getVcChildFolder());

		po.setNfilesize(uploadFile.length());
		po.setVcDelFlag(0);
		po.setDtLastDown(new Date());
		po.setVcDid(OrgUtil.getRootOrgId());
		DbUtil.addPo(po);
		Date creatDate = new Date();
		if ("true".equals(saveType)) { // 判断是否使用文件服务器
			// 使用文件服务器
			NetFileUtil.saveFileOnFileServer(uploadFile, fileId+fileType, creatDate,
					fileDir);
		} else {
			// 不使用文件服务器
			NetFileUtil
					.saveFileOnWebServer(uploadFile, fileId+fileType, creatDate, fileDir);
		}
	}

	public static String getFilePath(String fileType) {
		if (fileType == null)
			fileType = "";
		if (fileType.indexOf("/") >1)
			fileType = fileType.replace("/", "/");
		if (fileType.indexOf("\\") >1)
			fileType = fileType.replace("\\", "\\");
		String dir = fileType + "/";
		String[] folder = DateTool.formatDate(new Date()).split("-"); // 根据添加日期生成目录格式
		for (int i = 0; i < folder.length; i++) {
			dir = dir + folder[i] + "/";
		}
		return dir;
	}

	/**
	 * 开发人： 小觜冰凉
	 * 开发时间： 2013-11-8 上午10:33:57
	 * 功能描述：将文件保存到文件服务器中
	 * 方法的参数和返回值
	 * @param uploadFile
	 * @param fileName
	 * @param creatDate
	 * @param fileType
	 * @throws AppException
	 * void
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static void saveFileOnFileServer(File uploadFile, String fileName,
			Date creatDate, String fileType) throws AppException {

		creatDate = new Date();
		FTPClient ftp_ = getFTPUpClient();

		try {
			if (fileType == null)
				fileType = "";
			if (fileType.indexOf("/") >= 0)
				fileType = fileType.replace("/", "_");
			if (fileType.indexOf("\\") >= 0)
				fileType = fileType.replace("\\", "_");
			try {
				ftp_.changeWorkingDirectory("/");
				ftp_.makeDirectory(fileType);
			} catch (Exception e) {
			}
			ftp_.changeWorkingDirectory("/" + fileType);
			String[] folder = DateTool.formatDate(creatDate).split("-"); // 根据添加日期生成目录格式
			for (int i = 0; i < folder.length; i++) {
				try {
					ftp_.makeDirectory(folder[i]); // 建立年，月，日的文件夹
				} catch (Exception e) {
				}
				String workDir = ftp_.printWorkingDirectory();
				ftp_.changeWorkingDirectory(workDir + "/" + folder[i]);
			}
			ftp_.setFileType(FTPClient.BINARY_FILE_TYPE); // 设定以二进制传输
			InputStream streamIn = new FileInputStream(uploadFile);
			ftp_.storeFile(fileName, streamIn);
		} catch (IOException e1) {
			e1.printStackTrace();
			throw new AppException("文件服务器发生错误，无法上传文件，请联系管理员");
		} finally {
			try {
				uploadFile.deleteOnExit();//删除缓存中的文件
				if (ftp_.isConnected()) {
					ftp_.logout();
					ftp_.disconnect();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 开发人： 小觜冰凉
	 * 开发时间： 2013-11-8 上午10:34:25
	 * 功能描述：将文件保存到文件服务器中
	 * 方法的参数和返回值
	 * @param uploadFile
	 * @param fileName
	 * @param creatDate
	 * @param fileType
	 * @throws AppException
	 * @throws IOException
	 * void
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static void saveFileOnWebServer(File uploadFile,
			String fileName, Date creatDate, String fileDir)
			throws AppException, IOException {
		String dir = RegeditUtil.getRegeditStringValue("WEB_SERVER_FILE_DIR");
		//如果没有配置本上目录，则使用默认路径D:/csmisfiles/ftpfile/
		dir=FrameworkContext.getAppPath()+"ftpfile/";
		if(dir.length()==0){
			dir = "D:/csmisfiles/ftpfile/";
		}
		//如果配置了多个目录，则使用最后一个目录做为存储根路径
		else if(dir.lastIndexOf(";")>=0){
			dir = dir.substring(dir.lastIndexOf(";")+1);
		}
		if (!dir.endsWith("/") && !dir.endsWith("\\"))
			dir = dir + "/";
		creatDate = new Date();
		if (fileDir == null)
		{
			fileDir = "";
		}
		if (fileDir.indexOf("/") >= 0)
		{
			System.out.println("935-fileDir="+fileDir);
			fileDir = fileDir.replace("/", "_");
			System.out.println("937-fileDir="+fileDir);
		}
		if (fileDir.indexOf("\\") >= 0)
		{
			System.out.println("941-fileDir="+fileDir);
			fileDir = fileDir.replace("\\", "_");
			System.out.println("942-fileDir="+fileDir);
		}
		dir += fileDir + "/";

		System.out.println("947-fileDir="+fileDir);
		// 根据添加日期生成目录格式
		String[] folder = DateTool.formatDate(creatDate).split("-");
		for (int i = 0; i < folder.length; i++) {
			dir = dir + folder[i] + "/";
			System.out.println("952-dir="+dir);
		}
		File saveFile = new File(dir);
		if (!saveFile.exists())
			saveFile.mkdirs();
		// 将文件保存到web服务器
		OutputStream streamOut = new FileOutputStream(dir + "/" + fileName);
		InputStream streamIn = new FileInputStream(uploadFile);
		int bytesRead;
		byte[] buffer = new byte[8129];
		while ((bytesRead = streamIn.read(buffer, 0, 8129)) != -1) {
			streamOut.write(buffer, 0, bytesRead);
		}
		streamOut.close();
		streamIn.close();
		uploadFile.deleteOnExit();//删除缓存中的文件
	}

	/**
	* 开发人：小觜冰凉
	* 开发日期: 2013-11-10  下午06:26:58
	 * 功能描述：图片文件下载，若本地存在要下载的图片文件，则直接下载；否则从远程同步到本地，然后下载
	* 方法的参数和返回值:
	* @param fileId
	* @param width
	* @param height
	*/
	public static void getDownPicFile(String fileId, int width, int height) {
		getDownPicFile(ServletActionContext.getResponse(),fileId,width,height);
	}

	/**
	 * 开发人： 小觜冰凉
	 * 开发时间： 2013-11-8 上午10:34:39
	 * 功能描述：图片文件下载，若本地存在要下载的图片文件，则直接下载；否则从远程同步到本地，然后下载
	 * 方法的参数和返回值
	 * @param response
	 * @param fileId
	 * @param width
	 * @param height
	 * void
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static void getDownPicFile(HttpServletResponse response,
			String fileId, int width, int height) {
		Connection con = null;
		InputStream bis = null;
		OutputStream bos = null;
		Statement st = null;
		ResultSet rs = null;
		String fileName = null, childFolder = null;
		long filesize = 0;
		boolean b=false;
		try {
			con = SystemContext.getConnection();
			String sqlStr = "SELECT VC_ID,VC_FILENAME,VC_CHILD$FOLDER,n_filesize FROM PUB_T_FILE_UPLOAD_LOG WHERE VC_ID ='"
					+ fileId + "'";
			st = con.createStatement();
			Logger.getLogger(NetFileUtil.class).info(sqlStr);
			rs = st.executeQuery(sqlStr);

			while (rs.next()) {
				fileId = rs.getString(1);
				fileName = rs.getString(2);
				childFolder = rs.getString(3);
				filesize = rs.getLong(4);
				break;
			}
			if (childFolder == null)
				childFolder = "oldfile/";
			if (fileName == null)
				fileName = fileId;
			response.setCharacterEncoding("UTF-8");
			//String tt=new String(fileName.getBytes("iso8859-1"),"GBK");
			response.setContentType("application/zip"); // MIME type for pdf doc
			response.setHeader("Content-disposition", "attachment; filename=\""
					+ new String(fileName.getBytes("GBK"),"ISO8859-1") + "\"");
			if(filesize>0)
				response.setHeader("Content-Length",""+filesize);
			bos = new BufferedOutputStream(response.getOutputStream());
			if (width<=0||height<=0) {// 下载图片
				bis = NetFileUtil.getInputStream(childFolder, fileId);
			} else {// 打开图片
				bis = NetFileUtil.getImage(childFolder, fileId, width,
						height);
			}
			byte[] buff = new byte[2048];
			int bytesRead;
			bytesRead = bis.read(buff, 0, buff.length);
			while (bytesRead >= 0) {
				bos.write(buff, 0, bytesRead);
				bytesRead = bis.read(buff, 0, buff.length);
			}
			sqlStr = "UPDATE PUB_T_FILE_UPLOAD_LOG SET DT_LAST_DOWN=SYSDATE(),N_DOWN=N_DOWN+1 WHERE VC_ID ='"
				+ fileId + "'";
			Logger.getLogger(NetFileUtil.class).info(sqlStr);
			st.executeUpdate(sqlStr);
		} catch (FileNotFoundException e) {
			b=true;
			Logger.getLogger(NetFileUtil.class).error("读取"+childFolder+fileName+"文件不存在！",e);
			//e.printStackTrace();
		} catch(SocketException e)
		{
			Logger.getLogger(NetFileUtil.class).error("读取"+childFolder+fileName+"文件时，出现ClientAbortException:  java.net.SocketException: Connection reset by peer: socket write error",e);
		}catch (IOException e) {
			b=true;
			Logger.getLogger(NetFileUtil.class).error("读取"+childFolder+fileName+"文件时，出现输入输出错误！",e);
			//e.printStackTrace();
		}
		catch (SQLException e) {
			b=true;
			Logger.getLogger(NetFileUtil.class).error("读取"+childFolder+fileName+"文件时，数据库发生链接异常",e);
			//e.printStackTrace();
		} catch (AppException e) {
			b=true;
			//e.printStackTrace();
		} finally {
			try {
				if(b)
				{
					bos.write("<script>alert('要下载的文件找不到，请联系管理员！');window.close();</script>".getBytes());
				}
				if(bis!=null)
				{
					bis.close();
				}
				if(bos!=null)
				{
					bos.flush();
					bos.close();
				}
			} catch (IOException e) {
			}
			try {
				rs.close();
				st.close();
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}

		}
	}

	/**
	 * 开发人： 小觜冰凉
	 * 开发时间： 2013-11-8 上午10:34:57
	 * 功能描述：文件下载，若本地存在要下载的文件，则直接下载；否则从远程同步到本地，然后下载
	 * 方法的参数和返回值
	 * @param fileId
	 * @param response
	 * void
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static void getDownFile(String fileId, HttpServletResponse response) {
		InputStream bis = null;
		OutputStream bos = null;
		boolean b=false;
		String fileName = null, childFolder = null;
		try {
			PubFileUploadLog po = (PubFileUploadLog) DbUtil.getPOByPk(PubFileUploadLog.class.getName(), fileId);
			bos = new BufferedOutputStream(response.getOutputStream());
			if(po!=null){
				fileId = po.getVcId();
				fileName = po.getVcFilename();
				childFolder = po.getVcChildFolder();
			}
			if (childFolder == null)
				childFolder = "oldfile/";
			if (fileName == null)
				fileName = fileId;

			response.setCharacterEncoding("UTF-8");
			//String tt=new String(fileName.getBytes("iso8859-1"),"GBK");
			response.setContentType("application/zip"); // MIME type for pdf doc
			response.setHeader("Content-disposition", "attachment; filename=\""
					+ new String(fileName.getBytes("GBK"),"ISO8859-1") + "\"");
			//bis = NetFileUtil.getInputStream(childFolder, fileId);
			bis =NetFileUtil.getInputStream2(fileId);
			if(bis==null)bis = new ByteArrayInputStream("文件未找到，请联系管理员！".getBytes());
			byte[] buff = new byte[8129];
			int bytesRead;
			while (-1 != (bytesRead = (bis.read(buff, 0, buff.length))))
				bos.write(buff, 0, bytesRead);


		} catch (FileNotFoundException e) {
			b=true;
			Logger.getLogger(NetFileUtil.class).error("读取"+childFolder+fileName+"文件不存在！");
			//e.printStackTrace();
		} catch(SocketException e)
		{
			Logger.getLogger(NetFileUtil.class).error("读取"+childFolder+fileName+"文件时，出现ClientAbortException:  java.net.SocketException: Connection reset by peer: socket write error");
		}catch (IOException e) {
			b=true;
			Logger.getLogger(NetFileUtil.class).error("读取"+childFolder+fileName+"文件时，出现输入输出错误！");
			//e.printStackTrace();
		} finally {
			try {
				if (b) {
					bos.write("<script>alert('要下载的文件找不到，请联系管理员！');window.close();</script>".getBytes());
				}
				if (bis != null) {
					bis.close();
				}
				if (bos != null) {
					bos.flush();
					bos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				LogUtil.logError("出现ClientAbortException:  java.net.SocketException: Connection reset by peer: socket write error",e);
			}
		}
	}


	public static boolean saveFileOnLocalFileServer(FTPClient sftp, FTPClient dist, String folder, String fileName) {
		// FTPClient ftp_ = getFTPUpClient();
		// FTPClient ftp_=getFtpDownClient("222.41.161.141","csmis","csmis");
		boolean b = false;
		if (sftp == null || dist == null)
			return b;
		InputStream in = null;
		try {

			sftp.changeWorkingDirectory(folder);
			in = sftp.retrieveFileStream(fileName);// 获取源文件流

			if (folder.indexOf("/") >= 0)
				folder = folder.replace("/", "_");
			if (folder.indexOf("\\") >= 0)
				folder = folder.replace("\\", "_");
			dist.changeWorkingDirectory("/");
			String[] foldertemp = folder.split("_");
			for (int i = 0; i < foldertemp.length; i++) {
				try {
					dist.makeDirectory(foldertemp[i]); // 建立文件夹
				} catch (Exception e) {
				}
				String workDir = dist.printWorkingDirectory();
				dist.changeWorkingDirectory(workDir + "/" + foldertemp[i]);
			}
			dist.setFileType(FTPClient.BINARY_FILE_TYPE); // 设定以二进制传输
			dist.setBufferSize(8 * 1024);
			dist.enterLocalPassiveMode();
			if (in != null) {
				dist.storeFile(fileName, in);
				b = true;
				if (226 != dist.getReplyCode())// 文件传输是否完成
				{
					b = false;
				}
			}
		} catch (CopyStreamException e) {
			e.printStackTrace();
		} catch (IOException e1) {
			Logger.getLogger(NetFileUtil.class).error("读取" + folder + fileName + "文件不存在！");
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return b;
	}


	/**
	 *
	 * 开发人：孙吉涛 开发日期：2009-2-12 功能描述：从注册表获取ftp
	 *
	 * @param
	 * @return
	 */
	public static FTPClient[] getFTPClientByRegedit() {
		String ftp =RegeditUtil.getRegeditStringValue("REMOTE_FTP_ACCESS");
		//ftp="192.168.2.109:csmis:csmis,192.168.2.109:csmis1:csmis1";
		if(StringUtil.isBlank(ftp))
			return null;
		String[] ftps = null;
		if (StringUtil.isNotBlank(ftp))
			ftps = ftp.split(",");
		FTPClient[] ftpClient=new FTPClient[ftps.length];
		if(ftps!=null&&ftps.length>0)
		{
			String ipsplit[];
			int i=0;
			for(String ftptemp:ftps)
			{
				ipsplit=ftptemp.split(":");
				ftpClient[i++]=getFTPDownClient(ipsplit[0],ipsplit[1],ipsplit[2]);
			}
		}
		return ftpClient;
	}
	public static FTPClient getFTPDownClient()
	{
		String ip = RegeditUtil.getRegeditStringValue("FTP_SERVER_IP");
		String username = RegeditUtil
				.getRegeditStringValue("FTP_SERVER_USERNAME");
		String pwd = RegeditUtil.getRegeditStringValue("FTP_SERVER_PWD");
		return getFTPDownClient(ip,username,pwd);
	}
	/**
	 *
	 * 开发人：孙吉涛 开发日期：2009-2-12 功能描述：获取ftp
	 *
	 * @param
	 * @return
	 */
	@SuppressWarnings("finally")
	public static FTPClient getFTPDownClient(String ip, String username, String pwd) {
		FTPClient ftp_ = null;
		int reply = -1;
		try {
			ftp_ = new FTPClient();
			ftp_.connect(ip);
			ftp_.login(username, pwd);
			reply = ftp_.getReplyCode();
			if (reply == 530) {
				Logger.getLogger(NetFileUtil.class).error("登录不成功，请查看ftp用户配置！");
				if (ftp_.isConnected()) {
					ftp_.disconnect();// 强制关闭
				}
				ftp_ = null;
			}

		} catch (IOException e) {
			ftp_.logout();
			Thread.sleep(100);// 延迟100ms
			if (!ftp_.isConnected()) {
				Logger.getLogger(NetFileUtil.class).error("关闭配置！");
			}
			if (ftp_.isConnected()) {
				ftp_.disconnect();// 强制关闭
			}
			ftp_ = null;
			Logger.getLogger(NetFileUtil.class).error(
					"远程连接不成功，请查看ftp配置！链接成功" + ftpSuccessedCnt + "次，logout释放" + ftpClosedCnt + "次，强制释放" + ftpQZClosedCnt
							+ "次，为关闭ftp链接为" + (ftpSuccessedCnt - ftpClosedCnt - ftpQZClosedCnt) + "个");
		} finally {
			if (ftp_ != null) {
				ftpSuccessedCnt++;
			}
			return ftp_;
		}
	}



	/**
	 *
	 * 开发人：孙吉涛 开发日期：2009-2-12 功能描述：释放ftp
	 *
	 * @param
	 * @return
	 */
	public static void freeFTPClient(FTPClient ftp_) {

		if (ftp_ != null) {
			try {
				ftp_.logout();
			} catch (IOException e) {
				// e.printStackTrace();
			}
			try {
				Thread.sleep(100);// 延迟100ms
			} catch (InterruptedException e) {
				// e.printStackTrace();
			}
			if (!ftp_.isConnected()) {
				// Logger.getLogger(NetFileOperater.class).error("关闭配置！");
				ftpClosedCnt++;
			}
			if (ftp_.isConnected()) {
				try {
					ftp_.disconnect();
					ftpQZClosedCnt++;
				} catch (IOException e) {
					e.printStackTrace();
				}// 强制关闭
			}
		}
	}

	public static void downCount(String fileId)
	{
		String sqlStr = "UPDATE PUB_T_FILE_UPLOAD_LOG SET DT_LAST_DOWN=SYSDATE(),N_DOWN=N_DOWN+1 WHERE VC_ID ='"
			+ fileId + "'";
		Logger.getLogger(NetFileUtil.class).info(sqlStr);
		try {
			DbUtil.executeSqlUpdate(sqlStr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String getFileName(String vcFileid) {
		String sql = "select VC_FILENAME from PUB_T_FILE_UPLOAD_LOG where vc_id='"+vcFileid+"'";
		return DbUtil.getFirstStringSqlQuery(sql);
	}

	public static List<PubFileUploadLog> getPubFileUploadLogs(String vcFileids[]) {
		String in_s=StringUtil.fromArrayToStr(vcFileids, true);
		String sql = "from PubFileUploadLog p where p.vcId in ("+in_s+")";
		List<PubFileUploadLog> l= (List<PubFileUploadLog>) DbUtil.executeHql(sql);
		return l;
	}


	/**
	 * 开发人： 小觜冰凉
	 * 开发时间： 2013-11-8 上午09:54:00
	 * 功能描述：通过文件的length获取文件大小
	 * 方法的参数和返回值
	 * @param fileS
	 * @return
	 * String
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static String FormetFileSize(long fileS) {//通过File的 length()方法数值传入
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

	/**
	 * @author ： 小觜冰凉
	 * @since： Oct 6, 2011 11:15:10 AM
	 * 功能描述：根据文件ID删除文件
	 * 方法的参数和返回值
	 * @param fileId
	 * void 
	 * ==================================
	 * 修改历史
	 * 修改人        修改时间      修改原因及内容
	 *
	 * ==================================
	 */
	public static void deleteFileById(String fileId){
        PubFileUploadLog fileInfo = (PubFileUploadLog)DbUtil.getPOByPk(PubFileUploadLog.class.getName(), fileId);
        if(fileInfo==null)
            return;
	       String saveType = RegeditUtil
           .getRegeditStringValue("USE_FTP_SERVER");
	       try{
	           if ("true".equals(saveType)) { // 判断是否使用文件服务器
	                // 使用文件服务器,删除文件服务器上的文件
	               FTPClient ftp_ = getFTPUpClient();
	               ftp_.changeWorkingDirectory("/" + fileInfo.getVcChildFolder());
	               ftp_.dele("/"+fileInfo.getVcChildFolder()+ "/"+fileInfo.getVcFilename());
	            } else {
	                // 不使用文件服务器，删除web服务器上的文件
	                String dir = RegeditUtil.getRegeditStringValue("WEB_SERVER_FILE_DIR");
	                //如果没有配置本上目录，则使用默认路径D:/csmisfiles/ftpfile/
	                if(dir.length()==0){
	                    dir = "D:/csmisfiles/ftpfile/";
	                }
	                //如果配置了多个目录，则使用最后一个目录做为存储根路径
	                else if(dir.lastIndexOf(";")>=0){
	                    dir = dir.substring(dir.lastIndexOf(";")+1);
	                }
	                if (!dir.endsWith("/") && !dir.endsWith("\\"))
	                    dir = dir + "/";
	                dir = dir + fileInfo.getVcChildFolder()+ fileInfo.getVcId();
	                File file = new File(dir);
	                file.delete();
	            }
	           DbUtil.executeSqlUpdate("delete from PUB_T_FILE_UPLOAD_LOG t where t.vc_id = '"+fileId+"'");  //删除数据库中的信息
	       }catch(Exception e){
	           e.printStackTrace();
	       }
	}

}
